#include "networkmanager.h"

NetworkManager::NetworkManager(QObject *parent) : QObject(parent)
{
    server = new QTcpServer(this);
    socket = new QTcpSocket(this);

    connect(server, &QTcpServer::newConnection, this, &NetworkManager::onNewConnection);
    connect(socket, &QTcpSocket::readyRead, this, &NetworkManager::onReadyRead);
    connect(socket, &QTcpSocket::disconnected, this, &NetworkManager::onDisconnected);
}

void NetworkManager::startServer()
{
    if(!server->listen(QHostAddress::Any, 12345)) {
        emit errorOccurred(tr("无法启动服务器：") + server->errorString());
        return;
    }
}

void NetworkManager::connectToServer(const QString &address, quint16 port)
{
    socket->connectToHost(address, port);
}

void NetworkManager::onNewConnection()
{
    QTcpSocket *clientSocket = server->nextPendingConnection();
    if(clientSocket) {
        socket = clientSocket;
        emit connectionEstablished();
    }
}

void NetworkManager::onReadyRead()
{
    QByteArray data = socket->readAll();
    emit dataReceived(data);
}

void NetworkManager::onDisconnected()
{
    emit errorOccurred(tr("连接断开"));
}